package com.restkeeper.store.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.store.entity.Credit;
import com.restkeeper.store.entity.CreditRepayment;
import com.restkeeper.store.mapper.CreditRepaymentMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;

@org.springframework.stereotype.Service("creditRepaymentService")
@Service(version = "1.0.0", protocol = "dubbo")
public class CreditRepaymentServiceImpl extends ServiceImpl<CreditRepaymentMapper, CreditRepayment> implements ICreditRepaymentService {
    @Autowired
    @Qualifier("creditService")
    private ICreditService creditService;

    @Override
    @Transactional
    public boolean repayment(CreditRepayment creditRepayment) {
        //获取当前挂账信息
        Credit credit = creditService.getById(creditRepayment.getCreditId());
        if (credit == null) {
            throw new BussinessException("挂账主体不存在!");
        }
        //判断金额
        if (creditRepayment.getRepaymentAmount() > credit.getCreditAmount()) {
            throw new BussinessException("还款金额超过欠款金额!");
        }
        creditRepayment.setCompanyName(credit.getCompanyName());
        creditRepayment.setCreditType(String.valueOf(credit.getCreditType()));
        creditRepayment.setUserName(StringUtils.isBlank(credit.getUserName()) ? "公司" : credit.getUserName());
        this.save(creditRepayment);

        //修改挂账欠款信息
        credit.setCreditAmount(credit.getCreditAmount() - creditRepayment.getRepaymentAmount());
        //记录总还款金额
        credit.setTotalRepaymentAmount(credit.getTotalRepaymentAmount() + creditRepayment.getRepaymentAmount());
        return creditService.saveOrUpdate(credit);
    }
}